define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
    var Controller = {
        index: function () {
            function debounce(handle, delay) {
                let time = null;
                return function () {
                    let self = this,
                        arg = arguments;
                    clearTimeout(time);
                    time = setTimeout(function () {
                        handle.apply(self, arg);
                    }, delay)
                }
            }
            var orderIndex = new Vue({
                el: "#orderIndex",
                data() {
                    return {
                        screenType: false,
                        orderScreenList: {},
                        orderList: [],
                        currentPage: 1,
                        totalPage: 0,
                        offset: 0,
                        limit: 10,
                        // form搜索
                        searchForm: {
                            status: "all",
                            create_time: [],
                            form_1_key: "order_sn",
                            form_1_value: "",
                            platform: "",
                            dispatch_type: "",
                            type: "",
                            pay_type: "",
                            activity_type: "",
                            goods_type: "",
                            goods_title: "",
                            form_2_key: "user_id",
                            form_2_value: "",
                            store_id: 'all'
                        },
                        searchFormInit: {
                            status: "all",
                            create_time: [],
                            form_1_key: "order_sn",
                            form_1_value: "",
                            platform: "",
                            dispatch_type: "",
                            type: "",
                            pay_type: "",
                            activity_type: "",
                            goods_type: "",
                            goods_title: "",
                            form_2_key: "user_id",
                            form_2_value: "",
                            store_id: 'all'
                        },
                        searchOp: {
                            status: "=",
                            create_time: "range",
                            order_sn: "like",
                            id: "=",
                            aftersale_sn: "=",
                            transaction_id: "=",
                            platform: "=",
                            dispatch_type: "=",
                            type: "=",
                            pay_type: "=",
                            activity_type: "like",
                            goods_type: "=",
                            goods_title: "like",
                            user_id: "=",
                            nickname: "like",
                            user_phone: "like",
                            consignee: "like",
                            phone: "like",

                            store_id: '='
                        },
                        totalMoney: '0.00',
                        // 发货
                        deliverRow: [],
                        deliverRowTable: [],
                        deliverDialog: false,
                        deliverForm: {
                            logistics_name: '',
                            express_number: '',
                        },
                        deliverFormInit: {
                            logistics_name: '',
                            express_number: '',
                        },
                        deliverSearch: '',
                        deliverOffset: 0,
                        deliverLimit: 6,
                        deliverCurrentPage: 1,
                        deliverTotalPage: 0,
                        deliverType: 'input',
                        deliverDisabled: false,

                        totalStatus: '',
                        optRecordDialog: false,
                        optList: [],
                        focusi: false,

                        choice_dialog: false,
                        choice_list: [],
                        choice_order_id: null,
                        choice_id: null,

                        selectStoreList: [],
                        searchWhree: '',
                        store_id_switch: false,
                        pickerOptions: {
                            shortcuts: [{
                                text: '今天',
                                onClick(picker) {
                                    const start = moment(new Date()).format('YYYY-MM-DD') + ' 00:00:00';
                                    const end = moment(new Date()).format('YYYY-MM-DD') + ' 23:59:59';
                                    picker.$emit('pick', [start, end]);
                                }
                            }, {
                                text: '昨天',
                                onClick(picker) {
                                    const start = moment(new Date()).add(-1, 'days').format('YYYY-MM-DD') + ' 00:00:00';
                                    const end = moment(new Date()).add(-1, 'days').format('YYYY-MM-DD') + ' 23:59:59';
                                    picker.$emit('pick', [start, end]);
                                }
                            }, {
                                text: '最近一周',
                                onClick(picker) {
                                    const end = moment(new Date()).format('YYYY-MM-DD') + ' 23:59:59';
                                    const start = moment(new Date()).add(-7, 'days').format('YYYY-MM-DD') + ' 00:00:00';
                                    picker.$emit('pick', [start, end]);
                                }
                            }, {
                                text: '最近一个月',
                                onClick(picker) {
                                    const end = moment(new Date()).format('YYYY-MM-DD') + ' 23:59:59';
                                    const start = moment(new Date()).add(-30, 'days').format('YYYY-MM-DD') + ' 00:00:00';
                                    picker.$emit('pick', [start, end]);
                                }
                            }, {
                                text: '上月',
                                onClick(picker) {
                                    const end = moment().month(moment().month() - 1).endOf('month').format('YYYY-MM-DD') + ' 23:59:59';
                                    const start = moment().month(moment().month() - 1).startOf('month').format('YYYY-MM-DD') + ' 00:00:00';
                                    picker.$emit('pick', [start, end]);
                                }
                            }]
                        },
                        // 批量发货
                        multipleSelection: [],
                        batchSendDialogVisible: false,
                        batchSendData: [],
                        batchSendNosend: [],
                        batchSendSuccess: [],
                        batchSendError: [],
                        loopIndex: 0,
                        loopStart: true,
                        batchSendActive: 'all',
                        batchSendType: '',
                        batchSendTypeVisible: false,
                        batchSendButtonType: null,
                        deliverByUploadTemplateForm: {
                            uploadFile: '',
                            express_code: '',
                            express_name: ''
                        }
                    }
                },
                mounted() {
                    if (new URLSearchParams(location.search).get('status')) {
                        this.searchForm.status = new URLSearchParams(location.search).get('status')
                    }
                    if (new URLSearchParams(location.search).get('datetimerange')) {
                        this.searchForm.create_time = new URLSearchParams(location.search).get('datetimerange').split(' - ')
                    }
                    if (new URLSearchParams(location.search).get('store_id')) {
                        this.searchForm.store_id = new URLSearchParams(location.search).get('store_id')
                        this.store_id_switch = true
                    }
                    this.reqOrderList()
                    // this.reqOrderScreenList()
                    // this.getStoreOptions();
                },
                methods: {
                    // 选择门店
                    changeStoreId(val) {
                        if (val) {
                            this.searchForm.store_id = '0';
                        } else {
                            this.searchForm.store_id = '';
                        }
                    },
                    getStoreOptions() {
                        let that = this;
                        Fast.api.ajax({
                            url: '/store/store/all',
                            loading: false,
                            type: 'GET',
                            data: {
                                search: that.searchWhree,
                            }
                        }, function (ret, res) {
                            that.selectStoreList = res.data;
                            let obj1 = {
                                id: '0',
                                name: '全部门店订单'
                            }
                            that.selectStoreList.unshift(obj1)
                            if (new URLSearchParams(location.search).get('store_id')) {
                                that.screenType = true;
                                that.searchForm.store_id = new URLSearchParams(location.search).get('store_id')
                            }
                            return false;
                        })
                    },
                    storeDebounceFilter: debounce(function () {
                        this.getStoreOptions()
                    }, 1000),
                    dataFilter(val) {
                        this.searchWhree = val;
                        this.storeDebounceFilter()
                    },
                    reqOrderScreenList() {
                        var that = this;
                        Fast.api.ajax({
                            url: 'shopro/order/order/getType',
                            loading: true,
                            type: 'GET',
                            data: {}
                        }, function (ret, res) {
                            that.orderScreenList = res.data
                            return false;
                        })
                    },
                    //请求
                    reqOrderList(offset, limit) {
                        var that = this;
                        if (offset == 0 && limit == 10) {
                            that.offset = offset;
                            that.limit = limit;
                        }
                        let filter = {}
                        let op = {}
                        for (key in that.searchForm) {
                            if (key != 'status' && key != 'create_time' && key != 'form_1_key' && key != 'form_1_value' && key != 'form_2_key' && key != 'form_2_value') {
                                if (that.searchForm[key] != '' && that.searchForm[key] != 'all') {
                                    filter[key] = that.searchForm[key];
                                }
                            } else if (key == 'form_1_value') {
                                if (that.searchForm[key] != '') {
                                    filter[that.searchForm.form_1_key] = that.searchForm[key];
                                }
                            } else if (key == 'form_2_value') {
                                if (that.searchForm[key] != '') {
                                    filter[that.searchForm.form_2_key] = that.searchForm[key];
                                }
                            } else if (key == 'create_time') {
                                if (that.searchForm[key]) {
                                    if (that.searchForm[key].length > 0) {
                                        filter[key] = that.searchForm[key].join(' - ');
                                    }
                                }
                            } else if (key == 'status') {
                                if (that.searchForm[key] != '' && that.searchForm[key] != 'all') {
                                    filter[key] = that.searchForm[key];
                                }
                            }
                        }
                        for (key in filter) {
                            op[key] = that.searchOp[key]
                        }
                        // return false;
                        Fast.api.ajax({
                            url: 'health/order/order/index',
                            loading: true,
                            type: 'GET',
                            data: {
                                filter: JSON.stringify(filter),
                                op: JSON.stringify(op),
                                offset: that.offset,
                                limit: that.limit,
                            }
                        }, function (ret, res) {
                            console.log(res)
                            that.orderList = res.data.rows;
                            that.totalPage = res.data.total;
                            that.focusi = false;
                            that.totalMoney = res.data.totalMoney;
                            return false;
                        })
                    },
                    handleSizeChange(val) {
                        this.offset = 0
                        this.limit = val
                        this.currentPage = 1;
                        this.reqOrderList()
                    },
                    handleCurrentChange(val) {
                        this.offset = (val - 1) * this.limit;
                        this.currentPage = 1;
                        this.reqOrderList()
                    },
                    //筛选
                    changeSwitch() {
                        this.screenType = !this.screenType;
                    },
                    screenEmpty() {
                        this.searchForm = JSON.parse(JSON.stringify(this.searchFormInit))
                    },
                    goOrderRefresh() {
                        this.focusi = true;
                        this.reqOrderList()
                    },
                    //导出 导出发货单
                    goExport(type = 'export') {
                        var that = this;
                        let filter = {}
                        let op = {}
                        for (key in that.searchForm) {
                            if (key != 'status' && key != 'create_time' && key != 'form_1_key' && key != 'form_1_value' && key != 'form_2_key' && key != 'form_2_value') {
                                if (that.searchForm[key] != '' && that.searchForm[key] != 'all') {
                                    filter[key] = that.searchForm[key];
                                }
                            } else if (key == 'form_1_value') {
                                if (that.searchForm[key] != '') {
                                    filter[that.searchForm.form_1_key] = that.searchForm[key];
                                }
                            } else if (key == 'form_2_value') {
                                if (that.searchForm[key] != '') {
                                    filter[that.searchForm.form_2_key] = that.searchForm[key];
                                }
                            } else if (key == 'create_time') {
                                if (that.searchForm[key]) {
                                    if (that.searchForm[key].length > 0) {
                                        filter[key] = that.searchForm[key].join(' - ');
                                    }
                                }
                            } else if (key == 'status' || key == 'store_id') {
                                if (that.searchForm[key] != '' && that.searchForm[key] != 'all') {
                                    filter[key] = that.searchForm[key];
                                }
                            }
                        }
                        for (key in filter) {
                            op[key] = that.searchOp[key]
                        }
                        window.location.href = Config.moduleurl + "/shopro/order/order/" + type + "?filter=" + JSON.stringify(filter) + "&op=" + JSON.stringify(op);
                    },
                    viewAftersale(aftersale_id) {
                        let that = this;
                        Fast.api.open("shopro/order/aftersale/detail?id=" + aftersale_id, "售后详情", {
                            callback() {
                                that.reqOrderList()
                            }
                        });
                    },
                    goDetail(id) {
                        let that = this;
                        Fast.api.open('shopro/order/order/detail?id=' + id, "查看详情", {
                            callback() {
                                that.reqOrderList()
                            }
                        });
                    },
                    goGroupon(type, id) {
                        let that = this;
                        if (id == 0) {
                            return false;
                        }
                        if (type == "groupon") {
                            parent.Fast.api.open(`shopro/activity/groupon/detail/id/${id}`, "查看详情", {
                                callback(data) {
                                    that.reqOrderList()
                                }
                            });
                        }
                    },
                    goOrderUser(id) {
                        let that = this;
                        Fast.api.open('shopro/user/user/profile?id=' + id, '查看下单用户', {
                            callback() {
                                that.reqOrderList();
                            }
                        })
                    },
                    optRecord(id) {
                        let that = this;
                        Fast.api.ajax({
                            url: `shopro/order/order/actions/id/${id}`,
                            loading: true,
                            data: {}
                        }, function (ret, res) {
                            that.optList = res.data;
                            that.optRecordDialog = true
                            return false;
                        })
                    },
                    deliverFilter(val) {
                        this.deliverSearch = val;
                        this.deliverOffset = 0;
                        this.deliverLimit = 6;
                        this.deliverCurrentPage = 1;
                        this.deliverDebounceFilter();
                    },
                    // 发货
                    changeExpressName(e) {
                        this.deliverForm.express_name = this.$refs[e][0].dataset.name
                    },
                    openDeliverDialog(row) {
                        this.deliverRow = row
                        this.deliverRowTable = row.order_goods
                        this.deliverDialog = true
                    },
                    deliverSelectionChange(val) {
                        let item_ids = []
                        val.forEach(i => {
                            item_ids.push(i.id)
                        })
                        this.deliverForm.item_ids = item_ids.join(',')
                    },
                    // 提交发货信息
                    async reqDeliver() {
                        var that = this;
                        let res = null
                        res = await Controller.orderApi.deliver(that.deliverRow.id, that.deliverForm)
                        if (res.code == 1) {
                            that.reqOrderList();
                            that.deliverDialog = false
                            that.deliverForm = JSON.parse(JSON.stringify(that.deliverFormInit));
                        }
                    },
                    // 关闭去发货弹框
                    closeDeliverDialog() {
                        this.deliverDialog = false;
                        this.deliverForm = JSON.parse(JSON.stringify(this.deliverFormInit));
                    },
                },
                watch: {
                    //去监听发货表单
                    deliverForm: {
                        handler: function (newVal) {
                            if (newVal.logistics_name && newVal.express_number) {
                                this.deliverDisabled = true
                            } else {
                                this.deliverDisabled = false
                            }
                        },
                        deep: true
                    },
                }
            })
        },
        //订单接口
        orderApi: {
            // 订单发货
            deliver(orderId, deliverForm) {
                let reqUrl = `health/order/order/deliver`;
                return new Promise(resolve => {
                    Fast.api.ajax({
                        url: reqUrl,
                        loading: true,
                        data: {
                            order_id: orderId,
                            logistics_name: deliverForm.logistics_name,
                            express_number: deliverForm.express_number
                        }
                    }, function (ret, res) {
                        resolve(res);
                        return false
                    }, function (ret, res) {
                        resolve(res);
                    })
                });
            },
        }
    }
    return Controller;
});